package com.example.dense_rack_server.WebSocket;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * websocket的处理类。
 * 作用相当于HTTP请求
 * 中的controller
 */
@Component
@Slf4j
@ServerEndpoint("/api/pushMessage/{userId}")
public class WebSocketServer {

    private static WebSocketServer webSocketServer;

    @PostConstruct  //关键点3
    public void init() {
        webSocketServer = this;
    }

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的WebSocket对象。
     */
    private static ConcurrentHashMap<String, Object> webSocketMap = new ConcurrentHashMap<>();

    /**
     * 连接建立成
     * 功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            webSocketMap.put(userId, session);
        } else {
            webSocketMap.put(userId, session);
        }
//        HashMap<String, Object> returnMap = new HashMap<>();
//        returnMap.put("command", "connect");
//        returnMap.put("code", 200);
//        returnMap.put("status", "ok");
//        sendMessage(session, JSONUtil.toJsonStr(returnMap));
        log.info("有新的连接");
    }

    /**
     * 连接关闭
     * 调用的方法
     */
    @OnClose
    public void onClose(Session session, @PathParam("userId") String userId) {
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
        }
        log.info("断开连接");
    }

    /**
     * 收到客户端消
     * 息后调用的方法
     *
     * @param message 客户端发送过来的消息
     **/
    @OnMessage
    public void onMessage(String message, Session session, @PathParam("userId") String userId) throws InterruptedException, IOException {
        log.info("用户消息:" + userId + ",报文:" + message);
        HashMap<String, Object> returnMap = new HashMap<>();
        JSONObject data = JSONUtil.parseObj(message);
        String command = data.getStr("command");

    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error, @PathParam("userId") String userId) {
        log.error("用户错误:" + userId + ",原因:" + error.getMessage());
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public static void sendMessage(Session session, String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送自定义消息
     **/
    public static void sendInfo(String message, String userId) throws IOException {
        log.info("发送消息到:" + userId + "，报文:" + message);
        if (StrUtil.isNotBlank(userId) && webSocketMap.containsKey(userId)) {
            ((Session) webSocketMap.get(userId)).getBasicRemote().sendText(message);
        } else {
            log.error("用户" + userId + ",不在线！");
        }
    }
}